package chain_to_chain

import (
	"chain_bridge_service/internal/code"
	"chain_bridge_service/internal/pkg/core"
	"chain_bridge_service/internal/services/chain_to_chain"
	"net/http"
)

type QueryData struct {
	UserId         string `form:"userId"`
	ChainConfigId0 string `form:"chainConfigId0"`
	ChainConfigId1 string `form:"chainConfigId1"`
	Token0         string `form:"token0"`
	Token1         string `form:"token1"`
}

func (h *handler) ApiList() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(QueryData)
		res := new(createResponse)
		if err := ctx.ShouldBindQuery(&req); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.ParamBindError,
				code.Text(code.ParamBindError)).WithError(err),
			)
			return
		}

		productList, err := h.chainService.ApiList(ctx, req.UserId)
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.GetProductListError,
				code.Text(code.GetProductListError)).WithError(err),
			)
			return
		}

		res.Code = code.StatusOK
		res.Data = productList
		res.Msg = code.Text(code.StatusOK)
		ctx.Payload(res)
	}
}

func (h *handler) GetRate() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(QueryData)
		res := new(createResponse)
		if err := ctx.ShouldBindQuery(&req); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.ParamBindError,
				code.Text(code.ParamBindError)).WithError(err),
			)
			return
		}

		data := new(chain_to_chain.CreateChainData)
		data.Token1 = req.Token1
		data.Token0 = req.Token0
		data.ChainConfigId0 = req.ChainConfigId0
		data.ChainConfigId1 = req.ChainConfigId1
		data.UserId = req.UserId

		productList, err := h.chainService.GetRate(ctx, data)
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.GetProductListError,
				code.Text(code.GetProductListError)).WithError(err),
			)
			return
		}

		result := make(map[string]interface{})
		result["rate"] = productList.Rate.String()
		result["maxNumber"] = productList.MaxNumber
		res.Code = code.StatusOK
		res.Data = result
		res.Msg = code.Text(code.StatusOK)
		ctx.Payload(res)
	}
}
